package drds.binlog.event;

import drds.binlog.LogByteBlock;
import drds.binlog.LogEvent;

import java.nio.ByteBuffer;
import java.util.UUID;

/**
 * @since mysql 5.6 / mariadb10
 */
public class GtidLogEvent extends LogEvent
{

    // / Length of the commit_flag in event encoding
    public static final int ENCODED_FLAG_LENGTH = 1;
    // / Length of SID in event encoding
    public static final int ENCODED_SID_LENGTH = 16;
    public static final int LOGICAL_TIMESTAMP_TYPE_CODE = 2;

    private boolean commitFlag;
    private UUID sid;
    private long gno;
    private Long lastCommitted;
    private Long sequenceNumber;

    public GtidLogEvent(LogHeader logHeader, LogByteBlock logByteBlock, FormatDescriptionLogEvent formatDescriptionLogEvent)
    {
        super(logHeader);

        final int commonHeaderLength = formatDescriptionLogEvent.commonHeaderLength;
        // final int postHeaderLengths = descriptionEvent.postHeaderLengths[headerPacket.type
        // - 1];

        logByteBlock.index(commonHeaderLength);
        commitFlag = (logByteBlock.getUint8BasedOnIndex() != 0); // ENCODED_FLAG_LENGTH

        byte[] bytes = logByteBlock.getData(ENCODED_SID_LENGTH);
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        long high = byteBuffer.getLong();
        long low = byteBuffer.getLong();
        sid = new UUID(high, low);

        gno = logByteBlock.getLong64BasedOnIndex();

        // support gtid lastCommitted and sequenceNumber
        // fix bug #776
        if (logByteBlock.hasRemaining() && logByteBlock.remaining() > 16 && logByteBlock.getUint8BasedOnIndex() == LOGICAL_TIMESTAMP_TYPE_CODE)
        {
            lastCommitted = logByteBlock.getLong64BasedOnIndex();
            sequenceNumber = logByteBlock.getLong64BasedOnIndex();
        }

        // ignore gtid info read
        // sid.copy_from((uchar *)ptr_buffer);
        // ptr_buffer+= ENCODED_SID_LENGTH;
        //
        // // SIDNO is only generated if needed, in get_sidno().
        // spec.gtid.sidno= -1;
        //
        // spec.gtid.gno= uint8korr(ptr_buffer);
        // ptr_buffer+= ENCODED_GNO_LENGTH;
    }

    public boolean isCommitFlag()
    {
        return commitFlag;
    }

    public UUID getSid()
    {
        return sid;
    }

    public long getGno()
    {
        return gno;
    }

    public Long getLastCommitted()
    {
        return lastCommitted;
    }

    public Long getSequenceNumber()
    {
        return sequenceNumber;
    }

    public String getGtidString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append(sid.toString()).append(":");
        sb.append(gno);
        return sb.toString();
    }
}
